package org.bw.bookstore.book.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.bw.bookstore.book.mapper.*;
import org.bw.bookstore.book.service.ReplenishmentService;
import org.bw.bookstore.common.entity.*;
import org.bw.bookstore.common.utils.ConstantSet;
import org.bw.bookstore.common.utils.JwtTokenUtils;
import org.bw.bookstore.common.utils.ResponseResult;
import org.bw.bookstore.common.utils.StringTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @program:wisdom_bookstore
 * @description:补货实现类
 * @author:liuwu
 * @create:2020-10-22 11:03
 **/
@Service
@Slf4j
public class ReplenishmentServiceImpl implements ReplenishmentService {

    @Autowired
    private BookDetailedMapper bookDetailedMapper;
    @Autowired
    private BookSingleMapper bookSingleMapper;
    @Autowired
    private ReplenishmentRecordMapper replenishmentRecordMapper;
    @Autowired
    private ReplenishmentTaskMapper replenishmentTaskMapper;
    @Autowired
    private StaffMemberMapper staffMemberMapper;

    @Override
    public ResponseResult makeReplenishmentRules(TbReplenishmentRules replenishmentRules) {
        return null;
    }

    /**
     * @Description: 制定补货任务
     * @Author: liuwu
     * @Date: 2020/10/25 18:41
     * @param replenishmentTask:
     * @return: com.bw.servercommon.utils.ResponseResult
     **/
    @Override
    public ResponseResult editReplenishmentTask(TbReplenishmentTask replenishmentTask) {
        ResponseResult result = ResponseResult.SUCCESS();

        //查询图书详情  判断是否有该类书
        TbBookDetailed tbBookDetailed = bookDetailedMapper.selectOne(new QueryWrapper<TbBookDetailed>()
                .lambda().eq(TbBookDetailed::getCode,replenishmentTask.getBookDetailedCode()));
        if(tbBookDetailed == null || !tbBookDetailed.getDeleted().equals(0)){
            return result.setFail("图书不存在，请先添加新品！或已下架!");
        }

        //制定任务
        replenishmentTask.setCode(StringTools.getRandomString(32));
        replenishmentTask.setCreateTime(new Date());
        replenishmentTask.setDeleted(0);
        replenishmentTask.setBookDetailedCode(replenishmentTask.getBookDetailedCode());
        replenishmentTask.setPlanReplenishmentNum(replenishmentTask.getPlanReplenishmentNum());
        replenishmentTask.setReplenishmentRulesCode("111");
        replenishmentTask.setFinishStatus(0);

        replenishmentTaskMapper.insert(replenishmentTask);
        //判断是否添加成功
        if(replenishmentTask.getId()!=null){
            return result;
        }
        return result.setFail("发布补货任务失败");
    }

    /**
     * @Description:录入图书单品
     * @Author: liuwu
     * @Date: 2020/10/25 18:41
     * @param bookDetailedCode:
     * @param rfid:
     * @param qrCode:
     * @param id:
     * @return: com.bw.servercommon.utils.ResponseResult
     **/
    @Override
    public ResponseResult entryBookSingle(String bookDetailedCode,String rfid,String qrCode,Integer id) {
        ResponseResult result = ResponseResult.SUCCESS();

        //查询工作人员是否存在 0-在职 1-离职
        TbStaffMember tbStaffMember = staffMemberMapper.selectById(id);
        if(tbStaffMember == null || !tbStaffMember.getDeleted().equals(0)) {
            return result.setFail("工作人员不存或已离职！");
        }
        //查询图书详情  判断是否有该类书
        TbBookDetailed tbBookDetailed = bookDetailedMapper.selectOne(new QueryWrapper<TbBookDetailed>()
        .lambda().eq(TbBookDetailed::getCode,bookDetailedCode));

        if(tbBookDetailed == null || !tbBookDetailed.getDeleted().equals(0)){
            return result.setFail("图书不存在，请先添加新品！或已下架!");
        }
        //库存+1
        tbBookDetailed.setBookInventoryLevel(tbBookDetailed.getBookInventoryLevel()+1);
        bookDetailedMapper.updateById(tbBookDetailed);

        //添加数据
        TbBookSingle bookSingle = new TbBookSingle();
        bookSingle.setCode(StringTools.getRandomString(32));
        bookSingle.setOnSellStatus(0);
        bookSingle.setCreateTime(new Date());
        bookSingle.setDeleted(0);
        bookSingle.setQrCode(qrCode);
        bookSingle.setRfid(rfid);
        bookSingle.setBookDetailedCode(bookDetailedCode);
        bookSingleMapper.insert(bookSingle);

        //判断是否添加成功
        if(bookSingle.getId()!=null){
            return result;
        }
        return result.setFail("录入图书失败");
    }

    /**
     * @Description: 生成补货记录
     * @Author: liuwu
     * @Date: 2020/10/25 18:41
     * @param replenishmentRecord:
     * @return: com.bw.servercommon.utils.ResponseResult
     **/
    @Override
    public ResponseResult generateReplenishmentRecord(TbReplenishmentRecord replenishmentRecord) {
        ResponseResult result = ResponseResult.SUCCESS();

        //查询补货记录
        TbReplenishmentRecord tbReplenishmentRecord = replenishmentRecordMapper.selectOne(new QueryWrapper<TbReplenishmentRecord>()
        .lambda().eq(TbReplenishmentRecord::getReplenishmentTaskCode,replenishmentRecord.getReplenishmentTaskCode()));

        //根据补货任务标识查询补货任务表
        TbReplenishmentTask tbReplenishmentTask = replenishmentTaskMapper.selectOne(new QueryWrapper<TbReplenishmentTask>()
                .lambda().eq(TbReplenishmentTask::getCode,replenishmentRecord.getReplenishmentTaskCode()));

        //判断是否存在  不存在啧添加  存在修改
        if(tbReplenishmentRecord!=null){
            //修改 实际补货量 +1
            tbReplenishmentRecord.setActualReplenishmentNum(tbReplenishmentRecord.getActualReplenishmentNum()+1);
            replenishmentRecordMapper.updateById(tbReplenishmentRecord);

            //查询修改实际补货量后的记录
            TbReplenishmentRecord replenishmentRecord1 = replenishmentRecordMapper.selectOne(new QueryWrapper<TbReplenishmentRecord>()
                    .lambda().eq(TbReplenishmentRecord::getId,tbReplenishmentRecord.getId()));

            replenishmentRecord1.setUpdateTime(new Date());
            //计算每次补货后的超出缺少量
            replenishmentRecord1.setExceedLack(replenishmentRecord1.getActualReplenishmentNum()-tbReplenishmentTask.getPlanReplenishmentNum());
            replenishmentRecordMapper.updateById(replenishmentRecord1);

            //判断计划补货量是否等于实际补货 等于则改变状态  以完成
            if(replenishmentRecord1.getActualReplenishmentNum()==tbReplenishmentTask.getPlanReplenishmentNum()){
                tbReplenishmentTask.setFinishStatus(1);
                replenishmentRecord1.setFinishTime(new Date());
                replenishmentTaskMapper.updateById(tbReplenishmentTask);
            }
            return result;
        }else {
            //查询工作人员是否存在
            TbStaffMember tbStaffMember = staffMemberMapper.selectOne(new QueryWrapper<TbStaffMember>()
                    .lambda().eq(TbStaffMember::getCode,replenishmentRecord.getStaffMemberCode()));
            if(tbStaffMember == null || !tbStaffMember.getDeleted().equals(0)) {
                return result.setFail("工作人员不存或已离职！");
            }

            //添加数据
            replenishmentRecord.setCreateTime(new Date());
            replenishmentRecord.setCode(StringTools.getRandomString(32));
            replenishmentRecord.setDeleted(0);

            replenishmentRecord.setReplenishmentTaskCode(replenishmentRecord.getReplenishmentTaskCode());
            replenishmentRecord.setStaffMemberCode(replenishmentRecord.getStaffMemberCode());
            replenishmentRecord.setActualReplenishmentNum(1);
            replenishmentRecord.setExceedLack(replenishmentRecord.getActualReplenishmentNum()-tbReplenishmentTask.getPlanReplenishmentNum());

            if(tbReplenishmentTask.getPlanReplenishmentNum()==1){
                tbReplenishmentTask.setFinishStatus(1);
                replenishmentRecord.setFinishTime(new Date());
                replenishmentTaskMapper.updateById(tbReplenishmentTask);
            }

            replenishmentRecordMapper.insert(replenishmentRecord);
            //判断是否添加成功
            if (replenishmentRecord.getId()!=null){
                return result;
            }
            return result.setFail("生成补货记录失败");
        }

    }

    /**
     * @Description: 查询全部补货记录
     * @Author: liuwu
     * @Date: 2020/10/25 18:42
     * @return: com.bw.servercommon.utils.ResponseResult
     **/
    @Override
    public ResponseResult getReplenishmentRecord() {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap<>(16);

        //查询全部列表
        List<TbReplenishmentRecord> tbReplenishmentRecord=replenishmentRecordMapper.getReplenishmentRecord();
        //加入集合
        resultMap.put("tbReplenishmentRecord",tbReplenishmentRecord);
        //传入返回类
        result.setResult(resultMap);
        return result;
    }

    @Override
    public ResponseResult getReplenishmentTaskByNoFinish() {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap<>(16);

        //根据状态=0  查询未完成的盘点任务
        List<TbReplenishmentTask> tbReplenishmentTask =replenishmentTaskMapper.getReplenishmentTaskByNoFinish();

        //判断是否有数据
        if(tbReplenishmentTask==null || tbReplenishmentTask.size()<=0){
            return result.setFail("暂无数据");
        }

        resultMap.put("tbReplenishmentTask",tbReplenishmentTask);
        result.setResult(resultMap);
        return result;
    }

    @Override
    public ResponseResult getReplenishmentTaskByFinish() {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap<>(16);

        //根据状态=1  查询完成的盘点任务
        List<TbReplenishmentTask> tbReplenishmentTask =replenishmentTaskMapper.getReplenishmentTaskByFinish();

        //判断是否有数据
        if(tbReplenishmentTask==null || tbReplenishmentTask.size()<=0){
            return result.setFail("暂无数据");
        }

        resultMap.put("tbReplenishmentTask",tbReplenishmentTask);
        result.setResult(resultMap);
        return result;
    }

    @Override
    public ResponseResult getReplenishmentTask() {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap<>(16);

        //查询完成的补货任务
        List<TbReplenishmentTask> tbReplenishmentTask =replenishmentTaskMapper.getReplenishmentTask();

        //查询全部任务
        if(tbReplenishmentTask==null || tbReplenishmentTask.size()<=0){
            return result.setFail("暂无数据");
        }

        resultMap.put("tbReplenishmentTask",tbReplenishmentTask);
        result.setResult(resultMap);
        return result;
    }

    @Override
    public ResponseResult loginStaffMember(String userName, String userPass) {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap<>(16);
        //查询工作人员
        TbStaffMember tbStaffMember= staffMemberMapper.selectOne(new QueryWrapper<TbStaffMember>()
                .eq("user_name",userName)
                .eq("deleted", ConstantSet.NOT)
                .last("limit 1"));
        //工作人员不存在
        if(tbStaffMember == null) {
            return result.setFail("工作人员不存在!");
        }

        //判断密码
        String password = userPass + "." +tbStaffMember.getUserSale();
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!tbStaffMember.getUserPass().equals(md5Password)){
            return result.setFail("工作人员密码不正确!");
        }

        //生成token
        String token = JwtTokenUtils.makeToken(tbStaffMember.getId(), tbStaffMember.getUserName(), "tbStaffMember");
        resultMap.put("tbStaffMember", tbStaffMember);
        resultMap.put("token", token);
        result.setResult(resultMap);
        return result;
    }

    //查询全部图书品类
    @Override
    public ResponseResult getBookDetailed() {
        ResponseResult result = ResponseResult.SUCCESS();
        HashMap<String, Object> resultMap = new HashMap<>(16);

        List<TbBookDetailed> tbBookDetaileds = bookDetailedMapper.selectList(new QueryWrapper<TbBookDetailed>());
        resultMap.put("tbBookDetaileds",tbBookDetaileds);
        result.setResult(resultMap);
        return result;
    }
}
